using UnityEngine;
using UnityEditor;
using System.Reflection;
using UnityEditorInternal;

namespace GameToolkit.Editor
{
    [CustomEditor(typeof(CustomRenderer), true)]
    public class CustomRendererEditor : UnityEditor.Editor
    {
        SerializedProperty m_Material;
        UnityEditor.Editor mMatEditor;
        MethodInfo mValidateMth;

        protected virtual string MaterialPropertyName { get { return "m_Material"; } }

        protected virtual void OnEnable()
        {
            m_Material = serializedObject.FindProperty(MaterialPropertyName);
            var tp = target.GetType();
            mValidateMth = tp.GetMethod("OnValidateMaterial", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod);
        }

        protected virtual void OnDisable()
        {
            if (mMatEditor != null)
            {
                GlobalUtil.Destroy(mMatEditor);
            }
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            EditorGUILayout.Space(3);
            bool validateMaterial = false;
            if (!m_Material.hasMultipleDifferentValues && m_Material.objectReferenceValue != null)
            {
                if (mMatEditor == null || mMatEditor.target != m_Material.objectReferenceValue)
                {
                    if (mMatEditor != null)
                        GlobalUtil.Destroy(mMatEditor);
                    mMatEditor = CreateEditor(m_Material.objectReferenceValue);
                    validateMaterial = true;
                }
                //var foldout = EditorGUILayout.InspectorTitlebar(m_Material.isExpanded, mMatEditor);
                //m_Material.isExpanded = foldout;
                EditorGUI.BeginDisabledGroup(true);
                mMatEditor.DrawHeader();
                EditorGUI.EndDisabledGroup();
                if (InternalEditorUtility.GetIsInspectorExpanded(m_Material.objectReferenceValue))
                {
                    EditorGUI.BeginChangeCheck();
                    mMatEditor.OnInspectorGUI();
                    validateMaterial |= EditorGUI.EndChangeCheck();

                }
            }
            if (validateMaterial && mValidateMth != null)
            {
                try
                {
                    mValidateMth.Invoke(target, new object[0]);
                }
                catch (System.Exception e)
                {
                    Debug.LogException(e);
                }
            }
        }
    }
}
